<script type="text/javascript" src="/jquery.js"></script>
<script type="text/javascript" src="/jquery.sparkline.js"></script>
<script>
    $.ajaxSetup({
        url: "tasks.json",
//        global: false,
        type: "GET",
        dataType: 'json',
        success: update_tasks,
//        error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); },
        timeout: 3000,
    });
    function periodial_update() {
        $.ajax({success: function(data){ update_tasks(data); setTimeout(periodial_update, 1000); },
                error:   function(){setTimeout(periodial_update, 0);}});
    }
    $(document).ready(function(){
        $('#cmd').focus();
        $("form").submit(function() {
            $.ajax({data:{'machine_ids': $('#machines').val() || [],
                          'cwd': $('#cwd').val(),
                          'cmd': $('#cmd').val()}});
            return false;
        });
        periodial_update();
    });
    function tdline(a) { return $.map(a, function(item, _){ return '<td>' + item + '</td>'; }).join(''); }
    function thline(a) { return $.map(a, function(item, _){ return '<th>' + item + '</th>'; }).join(''); }
    function deltask(taskid) { $.ajax({data:{'del': taskid}}); }

    function mover() { $(this).css('background', '#FFF7BF'); }
    function mout() { $(this).css('background', '#FFF'); }

    function update_tasks(data) {
        var rows = $.map(data.tasks, function(task, _){
            var color = '#f99';
            if (task.status=='new') color = '#fff';
            if (task.status=='taken') color = '#9f9';
            if (task.status==0) color = '#ccc';
            var line1 = '<tr style="background-color:' + color + '">' +
                        tdline([//'<div onmouseover="mover()" onmouseout="mout()" onclick="deltask(\'' + item._id + '\')">[x]</div>',
                                '<input type=button onclick="deltask(\'' + task._id + '\')" value="x">',
                                '[+]',
                                task._id,
                                task.machine_id,
                                task.cwd,
                                task.cmd,
                                task.status
                                //item.progress.join('<br>')
                                ]) +
                        '</tr>';
            var line2 = '<tr><th></th><th></th><td colspan=6>'+
                        '<pre style="background-color:black; color:#ccc">'+task.stdout+'</pre>'+
                        '<pre style="background-color:black; color:#ccc">'+task.stderr+'</pre>'+
                        '</td></tr>';
            return line1 + line2;
        });
        $("#cur_tasks").html('<table style="background-color:white">' +
                             '<tr>' + thline(['', '', 'id', 'machine_id', 'cwd', 'cmd', 'status']) + '</tr>' +
                             rows.join('') +
                             '</table>');

        var rows2 = $.map(data.machines, function(si, _){
            var line1 = '<tr style="background-color:' + 'pink' + '">' +
                        tdline([si.time + si.age,
                                si.machine_id,
                                si.hostname,
                                si.uptime,

                                '<span class="inlinela5">'+
                                    $.map( data.history[si.machine_id], function(oldsi, _) {
                                        return oldsi.time+':'+oldsi.la5;
                                    }).join() +
                                '</span> '+
                                si.la1+' '+si.la5+' '+si.la10,

                                si.rproc+'/'+si.nproc,
                                '<span class="inlinepie">'+
                                    si.memory.Active+','+
                                    (si.memory.MemTotal-si.memory.MemFree-si.memory.Active)+','+
                                    si.memory.MemFree+
                                '</span> '+
                                Math.round(si.memory.Active/1024/1024)+'Mb '+
                                Math.round(si.memory.MemFree/1024/1024)+'Mb '+
                                Math.round(si.memory.MemTotal/1024/1024)+'Mb ',

                                // number of active tasks on this machine
                                data.tasks.filter(function(task) {
                                    return si.machine_id==task.machine_id && task.status=='taken';
                                }).length
                                //item.version.kernel,
                                //item.version.gcc,
                                //item.version.geoip,
                                //item.version.erlang,
                                ]) +
                        '</tr>';
            return line1;
        });

        $("#cur_monitor").html( '<table style="background-color:white">' +
                                rows2.join('') +
                                '</table>');

        var now = 0.001 * new Date().getTime();
        $('.inlinela5').sparkline('html', {spotRadius:0, fillColor:false, lineWidth:2, width:'90px',
            normalRangeMin:0, normalRangeMax:1.0, chartRangeMinX:now-3*3600, chartRangeMaxX:now});
//        $('.inlinela5').sparkline([1], {composite: true});

        $('.inlinepie').sparkline('html', {type: 'pie', sliceColors: ['red','yellow','black']});



        var saved = $("#machines").val() || [];
        $("#machines").empty();
        //$("#machines").append('<option>None</option>');
        //$("#machines").append('<option>All</option>');
        //$("#machines").append('<option>Any</option>');
        $.each(data.machines, function(_, item) {
            $("#machines").append('<option value="'+ item.machine_id + '">' + item.machine_id + ' ' + item.hostname + '</option>');
        });
        $("#machines").val(saved);
    }
</script>

<span class="taskinfo">
<form action="javascript:void()">
<table>
<tr><th></th><th>Add Task</th></tr>
<tr><th>Machine(s)</th><td><select multiple="multiple" id="machines" name="machine_id" size=10>
</select></td></tr>
<!-- <tr><th>Name</th>   <td><input type=text name="name" size=33></td></tr> -->
<!-- <tr><th>Binary</th> <td><textarea name="Text" rows="2" cols="33"></textarea></td></tr> -->
<tr><th>Cwd</th>    <td><input type=text id="cwd" name="cwd" size=33></td></tr>
<tr><th>Cmd</th>    <td><input type=text id="cmd" name="cmd" size=33></td></tr>
<tr><th></th>       <td><input type=submit name="new"></td></tr>
</table></form>
</span>

<span>
 <div id="title">Monitor</div>
 <div id="cur_monitor" class=""></div>
</span>

<span>
 <div id="title">Current tasks</div>
 <div id="cur_tasks" class=""></div>
</span>
